package org.jeecg.modules.wms.stockTake.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import org.jeecg.modules.wms.common.constant.CommonWms;
import org.jeecg.modules.wms.inventory.entity.WmsInventory;
import org.jeecg.modules.wms.inventory.mapper.WmsInventoryMapper;
import org.jeecg.modules.wms.stockTake.entity.WmsStockTake;
import org.jeecg.modules.wms.stockTake.mapper.WmsStockTakeMapper;
import org.jeecg.modules.wms.stockTake.service.IWmsStockTakeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 盘点单
 * @Author: jeecg-boot
 * @Date:   2023-12-21
 * @Version: V1.0
 */
@Service
public class WmsStockTakeServiceImpl extends ServiceImpl<WmsStockTakeMapper, WmsStockTake> implements IWmsStockTakeService {

    @Autowired
    private WmsInventoryMapper wmsInventoryMapper;

    @Override
    @Transactional
    public void stockEdit(WmsStockTake wmsStockTake) {
        WmsStockTake stockTake = this.baseMapper.selectById(wmsStockTake.getId());
        if (wmsStockTake.getTakeType().equals(CommonWms.OPENLY_TAKE)){
            wmsStockTake.setTakeCyQua(Convert.toStr(NumberUtil.sub(wmsStockTake.getTakeQua(),wmsStockTake.getBaseCount())));
            wmsStockTake.setTakeStatus(CommonWms.TAKE_STATUS_YWC);
        }else {
            WmsInventory wmsInventory = wmsInventoryMapper.selectById(stockTake.getInventoryId());
            wmsStockTake.setTakeCyQua(Convert.toStr(NumberUtil.sub(wmsStockTake.getTakeQua(),wmsInventory.getBaseCount())));
            wmsStockTake.setTakeStatus(CommonWms.TAKE_STATUS_YWC);
        }
        this.baseMapper.updateById(wmsStockTake);
    }

    @Override
    @Transactional
    public void adjustAccount(List<String> asList) {
        List<WmsStockTake> wmsStockTakes = this.baseMapper.selectBatchIds(asList);
        for (WmsStockTake wmsStockTake : wmsStockTakes) {
            //盘点完成才可以进行调账
            if (wmsStockTake.getTakeStatus().equals(CommonWms.TAKE_STATUS_YWC)){
                WmsInventory wmsInventory = wmsInventoryMapper.selectById(wmsStockTake.getInventoryId());
                wmsInventory.setBaseCount(wmsStockTake.getTakeQua());
                wmsInventoryMapper.updateById(wmsInventory);

                wmsStockTake.setTakeStatus(CommonWms.TAKE_STATUS_TZ);
                this.baseMapper.updateById(wmsStockTake);
            }
        }
    }
}

